package com.bobamrz.frontend;

import java.io.IOException;
import java.security.InvalidParameterException;
import java.util.List;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.bobamrz.domain.Document;
import com.bobamrz.service.DocStatusService;
import com.bobamrz.service.DocumentService;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 * @author Vladimir Morozov, Jevgeni Krutov
 *
 */
public class DocumentViewServlet extends SecuredSuperServlet {
	
	private Logger log = Logger.getLogger(DocumentViewServlet.class);

	/**
	 * 
	 */
	private static final long serialVersionUID = 461051363305070386L;
	
	private HeaderAndMenuDataLoader headerAndMenuDataLoader = new HeaderAndMenuDataLoader();

	protected void securedGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String catalog = request.getParameter("catalog");	
		log.debug(catalog);
		if (catalog == null || catalog.equals("")) {
			throw new InvalidParameterException();
		}
		
		DocumentService documentService = new DocumentService();
		String paste = request.getParameter("paste");	
		log.debug(paste);
		if(paste != null && paste.equals("true")) {
			List<Long> clipboard = (List<Long>) request.getSession(false).getAttribute("clipboard");
			if(clipboard!=null) {
				documentService.changeDocumentsCatalog(clipboard, Long.parseLong(catalog));
				request.getSession(false).setAttribute("clipboard", null);
			}
		}
		
		
		Gson gson = new GsonBuilder().serializeNulls().create();	
		DocStatusService statusService = new DocStatusService();
		List<Map<String, String>> availableStatuses = statusService.getAvailableStatuses();
		String availableStatusesJson = gson.toJson(availableStatuses);
		request.setAttribute("availableStatuses", availableStatusesJson);
		
		headerAndMenuDataLoader.load(request);

		
		List<Document> docList = documentService.getDocumentList(Long.parseLong(catalog));
		log.debug("number of docs: "+docList.size());
		request.setAttribute("docList", docList);
		
		request.setAttribute("pageToLoad", "/WEB-INF/pages/docView.jsp");
		RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/pages/mainPage.jsp");
		dispatcher.forward(request, response);
	}
	
}
